import { createRouter, createWebHistory } from 'vue-router'
import Login from "../components/Login.vue"
import Home from "../views/Home.vue"
import DingTalkCallback from "../components/DingTalkCallback.vue"
import Profile from "../views/Profile.vue"
import Orders from "../views/Orders.vue"
import OrderDetail from "../views/OrderDetail.vue"
import Chat from "../views/Chat.vue"
import QA from "../views/QA.vue"
import CozeAI from "../views/CozeAI.vue"
import AttractionDetail from "../views/AttractionDetail.vue"

const routes = [
    { 
        path: '/', 
        redirect: '/home'
    },
    { 
        path: '/login', 
        component: Login,
        meta: { requiresAuth: false }
    },
    { 
        path: '/dingding-callback', 
        component: DingTalkCallback,
        meta: { requiresAuth: false }
    },
    { 
        path: '/home', 
        component: Home,
        meta: { requiresAuth: true }
    },
    { 
        path: '/profile', 
        component: Profile,
        meta: { requiresAuth: true }
    },
    { 
        path: '/orders', 
        component: Orders,
        meta: { requiresAuth: true }
    },
    { 
        path: '/orders/:id', 
        component: OrderDetail,
        meta: { requiresAuth: true }
    },
    { 
        path: '/attractions/:id', 
        component: AttractionDetail,
        meta: { requiresAuth: true }
    },
    { 
        path: '/chat', 
        component: Chat,
        meta: { requiresAuth: true }
    },
    { 
        path: '/qa', 
        component: QA,
        meta: { requiresAuth: true }
    },
    { 
        path: '/coze', 
        component: CozeAI,
        meta: { requiresAuth: true }
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    
    if (to.meta.requiresAuth && !token) {
        // 需要登录但未登录，跳转到登录页
        next('/login')
    } else if (to.path === '/login' && token) {
        // 已登录访问登录页，跳转到首页
        next('/home')
    } else {
        next()
    }
})

export default router